﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Configuration;
using System.Web.Configuration;

namespace SPWP.OpinionPoll
{
    public class QueryAnswer
    {
        private string listLocation = WebConfigurationManager.AppSettings["listpoll"].ToString();

        public string SPPollSite { get; set; }
        public string SPPollList { get; set; }

        string spsite;

        public QueryAnswer(string splist)
        {
            spsite = SPPollSite;
            SPPollList = splist;
        }

        /// <summary>
        /// Add new answer
        /// </summary>
        /// <param name="itemAdd">New poll answer details</param>
        /// <returns>Status message</returns>
        public string AddAnswer(PollAnswer itemAdd)
        {
            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        bool unSafeUpdate = objWeb.AllowUnsafeUpdates;
                        objWeb.AllowUnsafeUpdates = true;

                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItem objItem = objList.Items.Add();

                        objItem["PollID"] = itemAdd.PollID;
                        objItem["Title"] = itemAdd.Answer.Trim();
                        objItem["DisplayOrder"] = itemAdd.SortOrder;

                        objItem.Update();
                        string status = String.Empty;
                        
                        // create new vote list
                        if (CreateVoteList(itemAdd.PollID))
                            status = "Option added successfully" + " and " + "new vote list created";
                        else
                            status = "Option added successfully";

                        objWeb.AllowUnsafeUpdates = unSafeUpdate;

                        return status;
                    }
                }
            }
            catch (Exception ex)
            {
                return String.Format("{0}: {1}", "Error", ex.Message);
            }
        }

        /// <summary>
        /// Edit existing answer details
        /// </summary>
        /// <param name="itemEdit">Latest answer details</param>
        /// <returns>Status message</returns>
        public string UpdateAnswer(PollAnswer itemEdit)
        {
            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        bool unSafeUpdate = objWeb.AllowUnsafeUpdates;
                        objWeb.AllowUnsafeUpdates = true;

                        SPQuery objQuery = new SPQuery();
                        string ID = itemEdit.ID.ToString();  // hidden field
                        objQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + itemEdit.ID + "</Value></Eq></Where>";
                        SPList objList = objWeb.Lists[SPPollList];

                        SPListItem objItem = objList.GetItemById(int.Parse(ID));

                        objItem["PollID"] = itemEdit.PollID;
                        objItem["Title"] = itemEdit.Answer.Trim();
                        objItem["DisplayOrder"] = itemEdit.SortOrder;

                        objItem.Update();

                        objWeb.AllowUnsafeUpdates = unSafeUpdate;

                        return "Option successfully updated";

                    }
                }
            }
            catch (Exception ex)
            {
                return String.Format("{0}: {1}", "Error", ex.Message);
            }

        }

        /// <summary>
        /// Delete poll answer
        /// </summary>
        /// <param name="delID">Answer ID to be deleted</param>
        /// <returns>Status message</returns>
        public string DeleteAnswer(int delID)
        {
            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        bool unSafeUpdate = objWeb.AllowUnsafeUpdates;
                        objWeb.AllowUnsafeUpdates = true;

                        SPQuery objQuery = new SPQuery();
                        string ID = delID.ToString();  // hidden field
                        objQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + ID + "</Value></Eq></Where>";
                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItem objItem = objList.GetItemById(int.Parse(ID));
                        objItem.Delete();

                        objWeb.AllowUnsafeUpdates = unSafeUpdate;

                        return "Option deleted successfully";
                    }

                }
            }
            catch (Exception ex)
            {
                return String.Format("{0}: {1}", "Error", ex.Message);
            }

        }

        /// <summary>
        /// Query one poll details
        /// </summary>
        /// <param name="pollID">Poll ID to be viewed</param>
        /// <returns>One poll details</returns>
        public List<PollAnswer> ViewPollAnswerByID(int pollID)
        {
            List<PollAnswer> foundAnswerList = new List<PollAnswer>();

            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        SPQuery query = new SPQuery();
                        string id = pollID.ToString();
                        query.ViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""Created"" /><FieldRef Name=""Author"" /><FieldRef Name=""DisplayOrder"" /><FieldRef Name=""Modified"" /><FieldRef Name=""Editor"" /><FieldRef Name=""ID"" /><FieldRef Name=""PollID"" />";
                        query.Query = @"<Query><Where><Eq><FieldRef Name=""PollID"" /><Value Type=""Number"">" + id + "</Value></Eq></Where></Query>";

                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItemCollection filteredItems = objList.GetItems(query);

                        foreach (SPListItem item in filteredItems)
                        {
                            if (pollID.Equals(Convert.ToInt32(item["PollID"])))
                            { 
                                PollAnswer foundAnswer = new PollAnswer();

                                foundAnswer.PollID = Convert.ToInt32(item["PollID"].ToString());
                                foundAnswer.ID = Convert.ToInt32(item["ID"].ToString());
                                foundAnswer.Answer = item["Title"].ToString().Trim();
                                foundAnswer.SortOrder = Convert.ToInt32(item["DisplayOrder"].ToString());
                                foundAnswer.CreatedDate =  DateTime.Parse(item["Created"].ToString());
                                foundAnswer.ModifiedDate = DateTime.Parse(item["Modified"].ToString());

                                char[] separator = { '#' };
                                string author = item["Author"].ToString().TrimStart(separator);
                                string editor = item["Editor"].ToString().TrimStart(separator);
                            
                                foundAnswer.CreatedBy = author;
                                foundAnswer.ModifiedBy = editor;

                                foundAnswerList.Add(foundAnswer);
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                //String.Format("{0}: {1}", ErrorMessage.Error, ex.Message);
            }

            return foundAnswerList;

        }

        /// <summary>
        /// Create new Voting List
        /// </summary>
        /// <param name="pollID">Poll ID</param>
        /// <returns>Flag creation status</returns>
        public bool CreateVoteList(int pollID)
        {
            bool isCreated = false;
            using (SPSite site = new SPSite(listLocation))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    bool unSafeUpdate = web.AllowUnsafeUpdates;
                    web.AllowUnsafeUpdates = true;

                    string listTitle = "Poll Votes-" + pollID.ToString();
                    string internalName = "Poll_Vote_Template.stp";

                    SPListTemplate t = null;

                    foreach (SPListTemplate template in web.Site.GetCustomListTemplates(web))
                    {
                        if (template.InternalName.Equals(internalName))
                        {
                            t = template;
                            break;
                        }
                    }

                    SPList checkFirst = web.Lists.TryGetList(listTitle);

                    if (null != checkFirst) // list already exist
                        return false;

                    if (t != null)
                        web.Lists.Add(listTitle, "Voting list for Poll ID " + pollID.ToString(), t);

                    //Set the Show in Quick Launch Property
                    //SPList voteList = web.Lists[listTitle];
                    //voteList.OnQuickLaunch = true;
                    //voteList.Update();

                    web.AllowUnsafeUpdates = unSafeUpdate;

                    isCreated = true;
                }

            }

            return isCreated;
        }

    }
}
